package org.dh2580.dev.tools.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author: hao.deng
 * @Date: 2019/7/25-下午4:13
 */
public class ThreadFactoryGenerator {

    public static ThreadFactory newThreadFactory(String threadPrefix, boolean daemon) {

        return new ThreadFactory() {

            private AtomicLong threadNo = new AtomicLong(0);

            @Override
            public Thread newThread(Runnable r) {
                SecurityManager sm = System.getSecurityManager();

                ThreadGroup threadGroup = sm != null ? sm.getThreadGroup() : Thread.currentThread().getThreadGroup();

                Thread t = new Thread(threadGroup, r, threadPrefix + "-" + threadNo.getAndIncrement());
                t.setDaemon(daemon);
                t.setPriority(Thread.NORM_PRIORITY);

                return t;
            }
        };
    }
}
